package com.qinhao.loveCrowdFunding.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.qinhao.loveCrowdFunding.handler.MyMessageHandler;
import com.qinhao.loveCrowdFunding.pojo.*;
import com.qinhao.loveCrowdFunding.req.*;
import com.qinhao.loveCrowdFunding.resp.*;
import com.qinhao.loveCrowdFunding.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.qinhao.loveCrowdFunding.enums.ResponseCodeEnum;

@RestController
@CrossOrigin
@RequestMapping("/information")
public class FundingInformationController {
    @Autowired
    private SimpleInformationService simpleInformationService;
    @Autowired
    private DetailInformationService detailInformationService;
    @Autowired
    private DescriptionService descriptionService;
    @Autowired
    private UserDataManageService userDataManageService;
    @Autowired
    private MyMessageHandler myMessageHandler;
    @Autowired
    private MessageService messageService;
    @Autowired
    private AdminController adminController;
    private SimpleInformationResponse simpleInformationResponse = SimpleInformationResponse.builder().build();
    @RequestMapping("/getSimple")
     public SimpleInformationResponse getSimpleInformation(@RequestBody SimpleInfoRequest simpleInfoRequest) {
        if (simpleInfoRequest.getPageSize() <= 0 || simpleInfoRequest.getCurrentPage() <= 0) {
            simpleInformationResponse.setResponseCode(ResponseCodeEnum.PARAMETERISERROR.getCode());
            return simpleInformationResponse;
        }
        try {
            SimpleInformationDTO simpleInformation = simpleInformationService.getSimpleInformation(simpleInfoRequest);
            List<SimpleInformationEntity> simpleInformationEntities = new ArrayList<>();
            // bo转为entity
            if (simpleInformation != null && simpleInformation.getList() != null ) {
                for (int i = 0; i < simpleInformation.getList().size(); i++) {
                    SimpleInformationEntity simpleInformationEntity = new SimpleInformationEntity();
                    BeanUtils.copyProperties(simpleInformation.getList().get(i), simpleInformationEntity);
                    simpleInformationEntity.setFundingStatus(getStatus(simpleInformation.getList().get(i).getFundingStatus()));
                    simpleInformationEntities.add(simpleInformationEntity);
                }
            }
            if (!simpleInformationEntities.isEmpty()) {
                simpleInformationResponse = SimpleInformationResponse.builder().pageFormation(simpleInformation.getPageFormation())
                        .simpleInformationBOList(simpleInformationEntities).build();
                for (int i = 0; i < simpleInformation.getList().size(); i++) {
                    simpleInfoRequest.setUserID(simpleInformation.getList().get(i).getUserId());
                    TelephoneNumberDTO telephoneNumber =
                            simpleInformationService.getTelephoneNumber(simpleInfoRequest.getUserID());
                    simpleInformationEntities.get(i).setTelephoneNumber(telephoneNumber.getTelephoneNumber());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String createDate = sdf.format(sdf.parse(simpleInformation.getList().get(i).getFundingCreateTime()));
                   simpleInformationEntities.get(i).setFundingCreateTime(createDate);
                    if (simpleInformationEntities.get(i).getFundingEndTime() != null) {
                        String endDate = sdf.format(sdf.parse(simpleInformationEntities.get(i).getFundingEndTime()));
                        simpleInformationEntities.get(i).setFundingEndTime(endDate);
                    }
                }
            }
            simpleInformationResponse.setResponseCode(ResponseCodeEnum.SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            simpleInformationResponse.setResponseCode(ResponseCodeEnum.PARAMETERISERROR.getCode());
            return simpleInformationResponse;
        }
        return simpleInformationResponse;
    }
    @RequestMapping("/writeDetailInformation")
    public DetailInformationResponse writeDetailInformation(@RequestBody DetailInformationRequest detailInformationRequest) {
        int userId = detailInformationRequest.getUserId();
        DetailInformationResponse detailInformationResponse = DetailInformationResponse.builder().build();
        if (detailInformationRequest.getUserId() == null) {
            //userId为null返回空
            detailInformationResponse.setResponseCode(ResponseCodeEnum.USERIDISNULL.getCode());
            return detailInformationResponse;
        }
        try {
            DetailInformationDTO detailInformationDTO =
                    detailInformationService.writeDetailInformation(detailInformationRequest);
            if (detailInformationDTO != null) {
                MessageWriteByUserIdEntity messageWriteByUserIdEntity = MessageWriteByUserIdEntity.builder().build();
                messageWriteByUserIdEntity.setUserId(userId);
                String content = "你的标题为" + detailInformationRequest.getTitle() + "的众筹信息已经提交成功，请耐心等待管理员审核";
                messageWriteByUserIdEntity.setTitle(content);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = sdf.format(new Date());
                messageWriteByUserIdEntity.setDate(date);
                MessageWriteByUserIdDTO messageWriteByUserIdDTO = messageService.writeUnreadMessageByUserId(messageWriteByUserIdEntity);
                if (messageWriteByUserIdDTO.getId() != null) {
                    myMessageHandler.sendMessageToUser(userId + "", content);
                }
                BeanUtils.copyProperties(detailInformationDTO, detailInformationResponse);
            }
            detailInformationResponse.setResponseCode(ResponseCodeEnum.SUCCESS.getCode());
        } catch (Exception e) {
            detailInformationResponse.setResponseCode(ResponseCodeEnum.FAIL.getCode());
            return detailInformationResponse;
        }
        return detailInformationResponse;
    }
    @RequestMapping("/getDescription")
    public DescriptionResponse getDescriptionBySimpleInformationId(@RequestBody DescriptionRequest descriptionRequest) {
        DescriptionResponse descriptionResponse = DescriptionResponse.builder().build();
        try {
            DescriptionDTO descriptionBySimpleInformationId =
                    descriptionService.getDescriptionBySimpleInformationId(descriptionRequest);
            if (descriptionBySimpleInformationId != null) {
                BeanUtils.copyProperties(descriptionBySimpleInformationId, descriptionResponse);
            }
            descriptionResponse.setResponseCode(ResponseCodeEnum.SUCCESS.getCode());
        } catch (Exception e) {
            descriptionResponse.setResponseCode(ResponseCodeEnum.FAIL.getCode());
            return descriptionResponse;
        }
        return descriptionResponse;
    }
    @RequestMapping("/updateDescription")
    public UpdateDescriptionResponse updateDescriptionByDetailInformationId(@RequestBody UpdateDescriptionRequest updateDescriptionRequest) {
        UpdateDescriptionResponse updateDescriptionResponse = UpdateDescriptionResponse.builder().build();
        try {
           UpdateAllowDTO allowUpdate = detailInformationService.isAllowUpdate(updateDescriptionRequest.getId());
            if (allowUpdate.getAllowUpdate()) {
                UpdateDescriptionDTO updateDescriptionDTO =
                        descriptionService.updateDescriptionBySimpleInformationId(updateDescriptionRequest);
                descriptionService.updateStatusToZero(updateDescriptionRequest);
                String message = "你的标题为" + updateDescriptionRequest.getTitle() + "的众筹项目已经修改成功，请等待管理员审核";
                adminController.sendMessage(message, Integer.parseInt(updateDescriptionRequest.getUserId()));
                if (updateDescriptionDTO != null) {
                    BeanUtils.copyProperties(updateDescriptionDTO, updateDescriptionResponse);
                }
                updateDescriptionResponse.setResponseCode(ResponseCodeEnum.SUCCESS.getCode());
            } else {
                updateDescriptionResponse.setResponseCode(ResponseCodeEnum.STATUSERROR.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateDescriptionResponse.setResponseCode(ResponseCodeEnum.FAIL.getCode());
            return updateDescriptionResponse;
        }
        return updateDescriptionResponse;
    }
    @RequestMapping("/deleteMySimple")
    public DeleteMySimpleResponse deleteMySimple(@RequestBody DeleteMySimpleRequest deleteMySimpleRequest) {
        DeleteMySimpleResponse deleteMySimpleResponse = DeleteMySimpleResponse.builder().build();
        try {
            DeleteAllowDTO allowDelete = simpleInformationService.isAllowDelete(deleteMySimpleRequest);
            if (allowDelete.getAllowDelete()) {
                DeleteMySimpleDTO deleteMySimpleDTO =
                        simpleInformationService.deleteSimpleAndDetail(deleteMySimpleRequest);
                deleteMySimpleResponse.setId(deleteMySimpleDTO.getId());
                deleteMySimpleResponse.setResponseCode(ResponseCodeEnum.SUCCESS.getCode());
            } else {
                deleteMySimpleResponse.setResponseCode(ResponseCodeEnum.STATUSERROR.getCode());
            }
        } catch (Exception e) {
            deleteMySimpleResponse.setResponseCode(ResponseCodeEnum.FAIL.getCode());
        }
        return deleteMySimpleResponse;
    }
    @RequestMapping("/getMySimple")
    public SimpleInformationResponse getMySimpleInformation(@RequestBody SimpleInfoRequest simpleInfoRequest) {
        if (simpleInfoRequest.getPageSize() <= 0 || simpleInfoRequest.getCurrentPage() <= 0) {
            simpleInformationResponse.setResponseCode(ResponseCodeEnum.PARAMETERISERROR.getCode());
            return simpleInformationResponse;
        }
        try {
            SimpleInformationDTO simpleInformation = simpleInformationService.getMySimpleInformation(simpleInfoRequest);
            List<SimpleInformationEntity> simpleInformationEntities = new ArrayList<>();
            // bo转为entity
            if (simpleInformation != null && simpleInformation.getList() != null) {
                for (int i = 0; i < simpleInformation.getList().size(); i++) {
                    SimpleInformationEntity simpleInformationEntity = new SimpleInformationEntity();
                    BeanUtils.copyProperties(simpleInformation.getList().get(i), simpleInformationEntity);
                    simpleInformationEntity.setFundingStatus(getStatus(simpleInformation.getList().get(i).getFundingStatus()));
                    simpleInformationEntities.add(simpleInformationEntity);
                }
            }
            if (!simpleInformationEntities.isEmpty()) {
                simpleInformationResponse = SimpleInformationResponse.builder().pageFormation(simpleInformation.getPageFormation())
                        .simpleInformationBOList(simpleInformationEntities).build();
                for (int i = 0; i < simpleInformation.getList().size(); i++) {
                    simpleInfoRequest.setUserID(simpleInformation.getList().get(i).getUserId());
                    TelephoneNumberDTO telephoneNumber =
                            simpleInformationService.getTelephoneNumber(simpleInfoRequest.getUserID());
                    simpleInformationEntities.get(i).setTelephoneNumber(telephoneNumber.getTelephoneNumber());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String createDate = sdf.format(sdf.parse(simpleInformation.getList().get(i).getFundingCreateTime()));
                    simpleInformationEntities.get(i).setFundingCreateTime(createDate);
                    if (simpleInformationEntities.get(i).getFundingEndTime() != null) {
                        String endDate = sdf.format(sdf.parse(simpleInformationEntities.get(i).getFundingEndTime()));
                        simpleInformationEntities.get(i).setFundingEndTime(endDate);
                    }
                }
            }
            simpleInformationResponse.setResponseCode(ResponseCodeEnum.SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            simpleInformationResponse.setResponseCode(ResponseCodeEnum.PARAMETERISERROR.getCode());
            return simpleInformationResponse;
        }
        return simpleInformationResponse;
    }
    @RequestMapping("/getTelephoneNumberById")
    public GetTelephoneNumberResponse getTelephoneNumberById(@RequestBody GetTelephoneNumberRequest getTelephoneNumberRequest) {
        GetTelephoneNumberResponse getTelephoneNumberResponse = GetTelephoneNumberResponse.builder().build();
        if (getTelephoneNumberRequest.getId() == null) {
            getTelephoneNumberResponse.setCode(ResponseCodeEnum.USERIDISNULL.getCode());
        }
        try {
            GetTelephoneNumberDTO telephoneNumberDTO = userDataManageService.getTelephoneNumberById(getTelephoneNumberRequest);
            if (telephoneNumberDTO != null) {
                BeanUtils.copyProperties(telephoneNumberDTO, getTelephoneNumberResponse);
            }
            getTelephoneNumberResponse.setCode(ResponseCodeEnum.SUCCESS.getCode());
        }catch (Exception e) {
            getTelephoneNumberResponse.setCode(ResponseCodeEnum.FAIL.getCode());
        }
        return getTelephoneNumberResponse;
    }

    @RequestMapping("/report")
    public ReportResponse report(@RequestBody ReportRequest reportRequest) {
        ReportResponse reportResponse = ReportResponse.builder().build();
        if (reportRequest.getSimpleInformationId() == null) {
            reportResponse.setCode(ResponseCodeEnum.SIMPLEINNFORMATIONIDISNULL.getCode());
            return reportResponse;
        }
        try {
            simpleInformationService.report(reportRequest);
            String reportMessage = "标题为" + reportRequest.getTitle() + "的众筹内容已经被你举报,请等待管理员进一步审核";
            String beReportedMessage = "你的标题为" + reportRequest.getTitle() + "的众筹内容被举报,现在对其做下线处理,请等待管理员的进一步审核结果";
            adminController.sendMessage(reportMessage, reportRequest.getReportUserId());
            adminController.sendMessage(beReportedMessage, reportRequest.getUserId());
            reportResponse.setCode(ResponseCodeEnum.SUCCESS.getCode());
        }catch (Exception e) {
            reportResponse.setCode(ResponseCodeEnum.FAIL.getCode());
        }
        return reportResponse;
    }

    //  积分下降到60分无法举报
    @RequestMapping("/canReportQuery")
    public CanReportQueryResponse canReportQuery(@RequestBody CanReportQueryRequest canReportQueryRequest) {
        CanReportQueryResponse canReportQueryResponse = CanReportQueryResponse.builder().build();
        if (canReportQueryRequest.getSimpleInformationId() == null) {
            canReportQueryResponse.setCode(ResponseCodeEnum.USERIDISNULL.getCode());
        }
        try {
            CanReportQueryDTO canReportQueryDTO = simpleInformationService.canReportQuery(canReportQueryRequest);
            if (canReportQueryDTO != null) {
                BeanUtils.copyProperties(canReportQueryDTO, canReportQueryResponse);
                canReportQueryResponse.setCode(ResponseCodeEnum.SUCCESS.getCode());
            }
        } catch (Exception e) {
            canReportQueryResponse.setCode(ResponseCodeEnum.FAIL.getCode());
        }
        return canReportQueryResponse;
    }

    // 是否可以发起众筹项目
    @RequestMapping("canPublishQuery")
    public CanPublishFundingResponse canPublish(@RequestBody CanPublishFundingQueryRequest canPublishFundingQueryRequest) {
        CanPublishFundingResponse canPublishFundingResponse = CanPublishFundingResponse.builder().build();
        try {
            Boolean canPublish = simpleInformationService.canPublish(canPublishFundingQueryRequest);
            if (canPublish) {
                canPublishFundingResponse.setIsCanPublish(1);
            } else {
                canPublishFundingResponse.setIsCanPublish(0);
            }
            canPublishFundingResponse.setCode(ResponseCodeEnum.SUCCESS.getCode());
        } catch (Exception e) {
            canPublishFundingResponse.setCode(ResponseCodeEnum.FAIL.getCode());
        }
        return canPublishFundingResponse;
    }

    public String getStatus(Integer id) {
        if (id == 0) {
            return "审核中...";
        }
        if (id == 1) {
            return "已发布...";
        }
        if (id == 2) {
            return "被举报...";
        }
        if (id == 3) {
            return "被驳回...";
        }
        return "已结束...";
    }

}
